#include "linked_queue.h"

// 初始化队列
void queue_init(queue_t *queue, int capacity){
    queue->head = NULL;
    queue->tail = NULL;
    queue->size = 0;
    queue->capacity = capacity;
}

// 队尾入队
int queue_append(queue_t *queue, int data){
    if(queue->size >= queue->capacity){
        return -1; // 队列已满, 入队失败
    }
    node_t *new_node = (node_t*)malloc(sizeof(node_t));
    if(new_node == NULL){
        perror("malloc failed");
        return -2; // 内存分配失败
    }

    new_node->data = data;
    new_node->next = NULL;
    if(queue->tail == NULL){
        queue->head = new_node;
        queue->tail = new_node;
    }else{
        queue->tail->next = new_node;
        queue->tail = new_node;
    }
    queue->size++;
    return 0; // 入队成功
}

// 队首出队
// 队列中默认不保存负数
int queue_pop(queue_t *queue){
    if(queue->size <= 0){
        return -1; // 队列为空, 出队失败
    }
    node_t *pop_node = queue->head;
    int data = pop_node->data;
    queue->head = pop_node->next;
    if(queue->head == NULL){
        queue->tail = NULL;
    }
    free(pop_node);
    queue->size--;
    return data; // 出队成功
}


// 打印队列
void queue_print(queue_t *queue){
    node_t *current = queue->head;
    for(int i = 0; i < queue->size; i++){
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n\n");
}